"""
用户CRUD操作
"""
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.crud.base import CRUDBase
from app.models.user import AdminUser
from app.schemas.user import UserCreate, UserUpdate
from app.core.security import get_password_hash, verify_password


class CRUDUser(CRUDBase[AdminUser, UserCreate, UserUpdate]):
    """用户CRUD"""
    
    async def get_by_username(
        self,
        db: AsyncSession,
        *,
        username: str
    ) -> Optional[AdminUser]:
        """根据用户名获取用户"""
        result = await db.execute(
            select(AdminUser).where(AdminUser.username == username)
        )
        return result.scalar_one_or_none()
    
    async def get_by_email(
        self,
        db: AsyncSession,
        *,
        email: str
    ) -> Optional[AdminUser]:
        """根据邮箱获取用户"""
        result = await db.execute(
            select(AdminUser).where(AdminUser.email == email)
        )
        return result.scalar_one_or_none()
    
    async def create(
        self,
        db: AsyncSession,
        *,
        obj_in: UserCreate
    ) -> AdminUser:
        """创建用户"""
        db_obj = AdminUser(
            username=obj_in.username,
            email=obj_in.email,
            password_hash=get_password_hash(obj_in.password),
            nickname=obj_in.nickname,
            avatar=obj_in.avatar,
            role_id=obj_in.role_id
        )
        db.add(db_obj)
        await db.commit()
        await db.refresh(db_obj)
        return db_obj
    
    async def authenticate(
        self,
        db: AsyncSession,
        *,
        username: str,
        password: str
    ) -> Optional[AdminUser]:
        """认证用户"""
        user = await self.get_by_username(db, username=username)
        if not user:
            return None
        if not verify_password(password, user.password_hash):
            return None
        return user


# 创建实例
user = CRUDUser(AdminUser)

